/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.dict.service.plugins  
 */
package com.apache.dict.service.plugins;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.CacheManager;
import com.apache.database.constant.SystemTools;
import com.apache.database.constant.Validator;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.dict.entity.DataItem;
import com.apache.dict.manager.CacheTacticsPlugin;
import com.apache.dict.vo.ItemListVo;

/**
 * description:  地区数据获取插件实现
 * @author dwusoft 创建时间：2015-11-4  
 * @Copyright(c)2014:北京--软件技术有限公司
 */
public class CityListPluginImpl implements PluginConnector {
	private Logger logger = Logger.getLogger(getClass().getName());

	private CacheTacticsPlugin cacheTactics;
	private CacheManager cache;

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.apache.api.manager.PluginConnector#execute(com.apache.api.vo.ParamsVo)  
	 */
	public Object execute(ParamsVo vo) throws Exception {
		String cateEname = Validator.getDefaultStr(String.valueOf(vo.getParams(("cateEname"))), "cty");
		String fatherValue = Validator.getDefaultStr(String.valueOf(vo.getParams(("fatherValue"))), "0");
		logger.info("加载数据字典地区省市区县信息 start-->cateEname=" + cateEname + ",fatherValue=" + fatherValue + ";vo.getParams="
				+ vo.getParams());
		ResultEntity result = new ResultEntity();
		if (Validator.isNull(cateEname)) {
			result.setMessage("查询失败！");
			result.setResult("false");
			return result;
		}
		Map itemkeys = new HashMap();
		if (getCache().checkCacheObject("city_json_" + cateEname)) {
			itemkeys = (Map) getCache().getCacheObjectByKey("city_json_" + cateEname);

			logger.info("从缓存获取数据字典地区信息：" + itemkeys.size());
		} else {
			List<DataItem> items = getItems(cateEname, fatherValue);
			jsonStr(items, itemkeys);

			logger.info("首次加载数据库获取数据字典地区信息：getItems size=" + items.size() + ",itemkeys=" + itemkeys.size());
			if (!itemkeys.isEmpty()) {//加入缓存
				getCache().createCacheObject("city_json_" + cateEname, itemkeys);
			}
		}
		if (!itemkeys.isEmpty()) {
			result.setMessage("查询成功！");
			result.setResult("true");
			result.setEntity(itemkeys);
			return result;
		} else {
			result.setMessage("查询失败！");
			result.setResult("false");
			return result;
		}
	}

	private void jsonStr(List<DataItem> items, Map itemkeys) {
		if (!Validator.isEmpty(items)) {
			List list = new ArrayList();
			for (DataItem item : items) {
				Map map = new HashMap();
				map.put("p", item.getItemValue() + ":" + item.getItemText());
				List<DataItem> ims = getItems(item.getCateEname(), item.getItemValue());
				List jss = jsonstr2(ims);
				if (!Validator.isEmpty(jss)) {
					map.put("c", jss);
				}
				list.add(map);
			}
			itemkeys.put("citylist", list);
		}
	}

	private List jsonstr2(List<DataItem> items) {
		List list = new ArrayList();
		if (!Validator.isEmpty(items)) {
			for (DataItem item : items) {
				Map map = new HashMap();
				map.put("n", item.getItemValue() + ":" + item.getItemText());
				List<DataItem> ims = getItems(item.getCateEname(), item.getItemValue());
				List jss = jsonstr3(ims);
				if (!Validator.isEmpty(jss))
					map.put("a", jss);
				list.add(map);
			}
		}
		return list;
	}

	private List jsonstr3(List<DataItem> items) {
		List list = new ArrayList();
		if (!Validator.isEmpty(items)) {
			for (DataItem item : items) {
				Map map = new HashMap();
				map.put("s", item.getItemValue() + ":" + item.getItemText());
				list.add(map);
			}
		}
		return list;
	}

	private List<DataItem> getItems(String cateEname, String fatherValue) {
		ItemListVo item = new ItemListVo();
		item.setCateEname(cateEname);
		item.setFatherValue(fatherValue);
		List<DataItem> items = cacheTactics.getDataItems(item);
		if (Validator.isEmpty(items)) {
			MethodParam param = new MethodParam("ByProperty", "", "", DataItem.class.getName());
			if (Validator.isNotNull(cateEname)) {
				param.setParams("cateEname", cateEname);
			}

			if (Validator.isNotNull(fatherValue)) {
				param.setParams("fatherValue", "'%" + fatherValue + "%' ");
			}
			param.setParams("orderList", " order by item_Value asc");
			return dataItemDao.select(param);
		}
		return items;
	}

	public void setCacheTactics(CacheTacticsPlugin cacheTactics) {
		this.cacheTactics = cacheTactics;
	}

	private CacheManager getCache() {
		if (null == cache) {
			cache = SystemTools.getInstance().getCache("");
		}
		return cache;
	}

	private IDao dataItemDao;

	public void setDataItemDao(IDao dataItemDao) {
		this.dataItemDao = dataItemDao;
	}
}
